<template>
  <div class="app-container pg-custom-table">
    <!-- page-zone begin -->
    <el-row :gutter="10">
      <el-col :span="5">
        <div class="zone-menu">
          <div class="zone-head">
            <h5>表格名列表</h5>
            <el-button class="add-table-btn" type="primary" plain icon="el-icon-plus" @click="showTable()">新增</el-button>
          </div>
          <div class="zoon-search">
            <el-input
              placeholder="搜索名称"
              clearable
              prefix-icon="el-icon-search"
              v-model="templateNameSearch"
              @input="tableFilter()">
            </el-input>
          </div>
          <!-- table-list begin -->
          <ul v-if="tableListData&&tableListData.length" class="table-list">
            <li class="list-item" v-for="(item, index) in tableListData" :key="index" :class="{'active': tableActive===item.id}">
              <div class="name" @click="showTableColumn(item.id, 'click')">{{ item.templateName }}</div>
              <div class="list-opera">
                <el-button
                  type="text"
                  class="opera-item"
                  @click="showTable(item)">修改</el-button>
                <el-button
                  type="text"
                  class="opera-item"
                  @click="delTable(item)">删除</el-button>
              </div>
            </li>
          </ul>
          <!-- table-list end -->
          <div v-else class="table-empty">暂无数据</div>
        </div>
      </el-col>
      <el-col :span="19">
        <!-- right-toolbar begin -->
        <div class="right-toolbar" v-if="tableListData && tableListData.length">
          <el-button v-if="!needBatchEdit" type="primary" plain icon="el-icon-plus" @click="addTitle()">新增</el-button>
          <el-button v-if="!needBatchAdd && !needBatchEdit" type="primary" plain icon="el-icon-plus" @click="handleBatchColumn('add')">批量新增</el-button>
          <span class="permi-btn">
            <el-button v-if="!needBatchAdd && !needBatchEdit" type="success" plain icon="el-icon-edit" @click="handleBatchColumn('edit')">批量修改</el-button>
            <el-button v-else type="primary" icon="el-icon-receiving" @click="tableColumnSubmit('all')">批量保存</el-button>
          </span>
        </div>
        <!-- right-toolbar end -->
        <!-- title-form begin -->
        <el-form
          ref="tableTitleForm"
          class="title-form"
          label-width="0"
          :model="tableTitleForm">
          <!-- table begin -->
          <el-table ref="pageTable" class="page-table mt10" :data="tableTitleForm.tableColumnData">
            <el-table-column
              show-overflow-tooltip
              prop="columnTitle"
              label="列标题"
              min-width="138">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isEdit" :prop="`tableColumnData.${scope.$index}.columnTitle`" :rules="{ required: true, message: '请输入列标题', trigger: 'blur' }">
                  <el-input v-model="scope.row.columnTitle" placeholder="请输入列标题" clearable></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.columnTitle }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="columnProperty"
              label="列属性"
              min-width="110">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isEdit" :prop="`tableColumnData.${scope.$index}.columnProperty`" :rules="{ required: true, message: '请输入列属性', trigger: 'blur' }">
                  <el-input v-model="scope.row.columnProperty" placeholder="请输入列属性" clearable></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.columnProperty }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="columnWidth"
              label="列宽度"
              min-width="70">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isEdit" :prop="`tableColumnData.${scope.$index}.columnWidth`" :rules="{ required: true, message: '请输入列宽度', trigger: 'blur' }">
                  <el-input v-model.number="scope.row.columnWidth" placeholder="请输入列宽度" :min="0" clearable></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.columnWidth }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="dataPostion"
              label="数据位置"
              min-width="72">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isEdit" :prop="`tableColumnData.${scope.$index}.dataPostion`">
                  <dg-dict-select dictType="column_align" v-model="scope.row.dataPostion"></dg-dict-select>
                </el-form-item>
                <span v-else>{{ scope.row.dataPostion | filterDict(dict.type['column_align']) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="supportSorting"
              label="支持排序"
              min-width="72">
              <template slot-scope="scope">
                <el-form-item :prop="`tableColumnData.${scope.$index}.supportSorting`">
                  <el-switch
                    v-model="scope.row.supportSorting"
                    :active-value="1"
                    :inactive-value="0"
                    @change="tableColumnChange($event, scope.$index)">
                  </el-switch>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="defaultDisplay"
              label="默认显示"
              min-width="72">
              <template slot-scope="scope">
                <el-form-item :prop="`tableColumnData.${scope.$index}.defaultDisplay`">
                  <el-switch
                    v-model="scope.row.defaultDisplay"
                    :active-value="1"
                    :inactive-value="0"
                    @change="tableColumnChange($event, scope.$index)">
                  </el-switch>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="sortOrder"
              label="排序序号"
              min-width="72">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isEdit" :prop="`tableColumnData.${scope.$index}.sortOrder`">
                  <el-input v-model.number="scope.row.sortOrder" placeholder="请输入排序序号" :min="0"></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.sortOrder }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="remark"
              label="备注"
              min-width="184">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isEdit" :prop="`tableColumnData.${scope.$index}.remark`">
                  <el-input type="备注" v-model="scope.row.remark" placeholder="请输入备注" clearable></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              v-if="!needBatchEdit"
              width="86"
              fixed="right">
              <template slot-scope="scope">
                <div class="opera-row">
                  <span class="permi-btn">
                    <el-button
                      v-if="!scope.row.isEdit && !needBatchAdd"
                      type="text"
                      class="opera-item"
                      @click="editTitle(scope.$index)">修改</el-button>
                    <el-button
                      v-if="scope.row.isEdit && !needBatchAdd"
                      type="text"
                      class="opera-item"
                      @click="tableColumnSubmit(scope.$index)">保存</el-button>
                  </span>
                  <el-button
                    v-show="!needBatchAdd||(needBatchAdd&&scope.row.isEdit)"
                    type="text"
                    class="opera-item"
                    @click="delColumn(scope.row.id, scope.$index)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- table end -->
        </el-form>
        <!-- title-form end -->
      </el-col>
    </el-row>
    <!-- page-zone end -->

    <!-- dialogColumnNum begin -->
    <el-dialog
      title="批量新增标题"
      width="360px"
      :close-on-click-modal="false"
      :visible.sync="dialogColumnNum">
      <el-form
        ref="dialogColumnNumForm"
        class="dialog-column-num-form mt20"
        label-width="82px"
        :rules="rulesColumnNum"
        :model="dialogColumnNumForm">
        <el-form-item label="标题数量" prop="columnNum">
          <el-input v-model="dialogColumnNumForm.columnNum" placeholder="请输入标题数量"></el-input>
        </el-form-item>
        <el-form-item label="排序叠加" prop="isSort">
          <dg-dict-radio dictType="judge_status" v-model="dialogColumnNumForm.isSort"></dg-dict-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="dialogLoading" @click="columnNumSubmit()">确 定</el-button>
        <el-button @click="dialogColumnNum = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- dialogColumnNum end -->

    <!-- dialogTable begin -->
    <el-dialog
      :title="`${titleMap[dialogStatus]}表`"
      width="360px"
      :close-on-click-modal="false"
      :visible.sync="dialogTable">
      <el-form
        ref="dialogTableForm"
        class="dialog-table-form mt20"
        label-width="58px"
        size="small"
        :rules="rulesTable"
        :model="dialogTableForm">
        <el-form-item v-if="dialogStatus==='edit'" v-show="false">
          <el-input type="hidden" v-model="dialogTableForm.id"></el-input>
        </el-form-item>
        <el-form-item label="表名" prop="templateName">
          <el-input v-model="dialogTableForm.templateName" placeholder="请输入表名"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="dialogLoading" @click="tableSubmit()">确 定</el-button>
        <el-button @click="dialogTable = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- dialogTable end -->
  </div>
</template>

<script>
import mixin from '@/utils/filtermixin/mixin';
import listmixin from '@/utils/list-mixin';
import { checkPositiveNumber } from '@/utils/validate';
import * as API_Table from '@/api/system/table';
let tableDataList = [];

export default {
  name: 'pg-custom-table',
  dicts: ['column_align'],
  mixins: [mixin, listmixin],
  data () {
    return {
      templateNameSearch: '', // 表名筛选
      tableListData: [], // 表格名列表
      tableActive: '', // 选中表名
      dialogStatus: 'new', // 默认新增
      titleMap: {
        'new': '新增',
        'edit': '修改'
      },
      dialogTable: false, // 表弹层
      dialogTableForm: { // 表表单
        id: undefined,
        templateName: undefined
      },
      rulesTable: { // 表弹层表单规则
        templateName: [
          { required: true, message: '请输入表名', trigger: 'blur' }
        ]
      },
      dialogLoading: false,
      // 批量新增标题
      dialogColumnNum: false,
      dialogColumnNumForm: {
        columnNum: undefined,
        isSort: 1
      },
      rulesColumnNum: {
        columnNum: [
          { required: true, validator: checkPositiveNumber, message: '请输入标题数量', trigger: 'blur' }
        ]
      },
      // 批量新增
      needBatchAdd: false,
      // 批量修改
      needBatchEdit: false,
      tableTitleForm: {
        tableColumnData: [] // 表对应的 '列' 列表字典
      },
      // 分页属性
      total: 0, // 记录总条数
      pageSize: 100, // 每页显示条数
      pageIndex: 1 // 当前页
    };
  },
  mounted () {
    // 获取页面数据
    this.getTableData();
  },
  methods: {
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {查询表格列表}
    */
    getTableData () {
      API_Table.getTableTemplate().then(response => {
        let _useData = response || [];
        this.tableListData = _useData;
        tableDataList = _useData;
        let _activeTable = [];
        if (this.tableActive || this.tableActive === 0) {
          _activeTable = tableDataList.filter(item => item.id === this.tableActive);
        };
        if ((_useData.length > 0 && !this.tableActive) || !_activeTable.length) {
          this.pageIndex = 1;
          this.showTableColumn(_useData[0].id);
        };
      });
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {显示表弹层}
    */
    showTable (_table) {
      this.resetForm('dialogTableForm');
      this.dialogStatus = _table ? 'edit' : 'new';
      this.dialogTable = true;
      if (_table) {
        this.$nextTick(() => {
          this.dialogTableForm = {
            id: _table.id,
            templateName: _table.templateName
          };
        });
      };
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {表名提交}
    */
    tableSubmit () {
      let _params = this.MixinClone(this.dialogTableForm);
      Promise.resolve(this.dialogStatus === 'edit' ? API_Table.editTableTemplate(_params) : API_Table.addTableTemplate(_params)).then(() => {
        this.dialogTable = false;
        this.getTableData();
      });
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {表名筛选}
    */
    tableFilter () {
      let _tableListData = this.MixinClone(tableDataList);
      this.tableListData = _tableListData.filter(item => item.templateName.indexOf(this.templateNameSearch) > -1);
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {删除表}
    */
    delTable (_table) {
      this.$confirm(`是否确定要删除表[${_table.templateName}]?`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API_Table.delTableTemplate(_table.id).then(() => {
          this.getTableData();
        });
      }).catch(() => {
        console.log('取消');
      });
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {查询表格的列}
    */
    showTableColumn (_id, _type) {
      const { tableColumnData } = this.tableTitleForm;
      let _next = true;
      if (_type === 'click') {
        for (let item of tableColumnData) {
          if (item.isEdit) {
            _next = false;
            break;
          };
        };
      };
      if (!_next) {
        this.$confirm('当前表有未保存的列，是否继续离开?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.showColumnMethod(_id);
        }).catch(() => {
          console.log('取消');
        });
      } else {
        this.showColumnMethod(_id);
      };
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {查询表格列方法}
    */
    showColumnMethod (_id) {
      this.needBatchAdd = false;
      this.needBatchEdit = false;
      this.tableActive = _id;
      let _params = {
        tableId: _id
      };
      API_Table.getTableColumn(_params).then(response => {
        let _useData = response.data || [];
        this.$set(this.tableTitleForm, 'tableColumnData', _useData);
      });
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {新增标题}
    */
    addTitle () {
      let _newColumn = {
        tableId: this.tableActive,
        columnTitle: '',
        columnProperty: '',
        columnWidth: '',
        dataPostion: 0,
        supportSorting: 0,
        defaultDisplay: 1,
        sortOrder: '',
        remark: '',
        isEdit: true
      };
      this.$nextTick(() => {
        let _tableColumnData = this.MixinClone(this.tableTitleForm.tableColumnData);
        _tableColumnData.unshift(_newColumn);
        this.$set(this.tableTitleForm, 'tableColumnData', _tableColumnData);
      });
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {批量新增标题}
    */
    handleBatchColumn (_type) {
      if (_type === 'add') {
        this.resetForm('dialogColumnNumForm');
        this.dialogColumnNum = true;
      } else {
        let { tableColumnData } = this.tableTitleForm;
        let _next = true;
        for (let item in tableColumnData) {
          if (item.isEdit) {
            _next = false;
            this.$msgWarning('新增项未保存，无法进行批量修改');
            break;
          };
        };
        if (_next) {
          this.needBatchEdit = true;
          this.editTitle();
        };
      };
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {批量新增标题数量}
    */
    columnNumSubmit () {
      this.$refs['dialogColumnNumForm'].validate((valid) => {
        if (valid) {
          const { columnNum, isSort } = this.dialogColumnNumForm;
          let { tableColumnData } = this.tableTitleForm;
          let _newColumns = [];
          let _lastSort = tableColumnData && tableColumnData.length ? tableColumnData[tableColumnData.length-1].sortOrder : 0;
          for (let i = 0; i < columnNum; i++) {
            let _sortOrder = !parseInt(isSort) ? '' : !_newColumns.length ? _lastSort + 10 : _newColumns[0].sortOrder + 10;
            _newColumns.unshift({
              tableId: this.tableActive,
              columnTitle: '',
              columnProperty: '',
              columnWidth: '',
              dataPostion: 0,
              supportSorting: 0,
              defaultDisplay: 1,
              sortOrder: _sortOrder,
              remark: '',
              isEdit: true
            });
          };
          tableColumnData = _newColumns.concat(tableColumnData);
          this.$nextTick(() => {
            this.needBatchAdd = true;
            this.tableTitleForm.tableColumnData = tableColumnData;
          });
          this.dialogColumnNum = false;
        } else {
          console.log('error submit!!');
          return false;
        };
      });
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {修改标题}
    */
    editTitle (_index) {
      let { tableColumnData } = this.MixinClone(this.tableTitleForm);
      if (_index || _index === 0) {
        let _editColumn = tableColumnData[_index];
        _editColumn.isEdit = true;
        this.$set(this.tableTitleForm.tableColumnData, _index, _editColumn);
      } else {
        let _tableColumnData = tableColumnData.map(item => {
          item.isEdit = true;
          return item;
        });
        this.$nextTick(() => {
          this.tableTitleForm.tableColumnData = _tableColumnData;
        });
      };
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {_index: all为批量保存}
    */
    tableColumnSubmit (_index) {
      let _params = [];
      let { tableColumnData } = this.tableTitleForm;
      if (_index === 'all') {
        console.log(this.needBatchAdd, this.needBatchEdit);
        let _service = API_Table.addBatchTableColumns;
        if (this.needBatchAdd) {
          _params = tableColumnData.filter(item => item.isEdit) || [];
          if (!_params.length) {
            this.$msgWarning('无需要保存的列');
            this.needBatchAdd = false;
            return;
          };
        } else {
          _params = tableColumnData;
          _service = API_Table.editBatchTableColumns;
        };
        this.$refs['tableTitleForm'].validate((valid) => {
          if (valid) {
            _service(_params).then(() => {
              this.needBatchAdd = false;
              this.needBatchEdit = false;
              this.showTableColumn(this.tableActive);
            });
          } else {
            console.log('error submit!!');
            return false;
          };
        });
      } else if (_index || _index === 0) {
        _params = tableColumnData[_index];
        let _validateFields = [`tableColumnData.${_index}.columnTitle`, `tableColumnData.${_index}.columnProperty`, `tableColumnData.${_index}.columnWidth`];
        let _validateData = [];
        this.$refs['tableTitleForm'].validateField(_validateFields, (valid) => {
          _validateData.push(valid);
        });
        if (_validateData.every(item => item === '')) {
          Promise.resolve(_params.id || _params.id === 0 ? API_Table.editTableColumns(_params) : API_Table.addTableColumn(_params)).then(() => {
            let _editColumn = this.tableTitleForm.tableColumnData[_index];
            _editColumn.isEdit = false;
            this.$set(this.tableTitleForm.tableColumnData, _index, _editColumn);
          });
        };
      };
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {非修改情况下，开关切换}
    */
    tableColumnChange (value, _index) {
      let _editColumn = this.tableTitleForm.tableColumnData[_index];
      if ((!_editColumn.id && _editColumn.id !== 0) || _editColumn.isEdit) {
        return;
      };
      API_Table.editTableColumns(_editColumn).then(() => {
        this.$set(this.tableTitleForm.tableColumnData, _index, _editColumn);
      });
    },
    /**
      * @date 2025/07/22
      * @author wolfMan
      * @description {删除列}
    */
    delColumn (_id, _index) {
      if (_id || _id === 0) {
        this.$confirm(`是否确定要删除此列吗?`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          API_Table.delTableColumn(_id).then(() => {
            let { tableColumnData } = this.tableTitleForm;
            tableColumnData.splice(_index, 1);
            this.$set(this.tableTitleForm, 'tableColumnData', tableColumnData);
          });
        }).catch(() => {
          console.log('取消');
        });
      } else {
        let { tableColumnData } = this.tableTitleForm;
        tableColumnData.splice(_index, 1);
        this.$set(this.tableTitleForm, 'tableColumnData', tableColumnData);
      };
    }
  }
};
</script>

<style lang="scss">
.pg-custom-table {
  .zone-menu {
    position: relative;
    height: calc(100vh - 80px);
    border: solid 1px #dedede;
    box-sizing: border-box;
    .zone-head {
      position: relative;
      .add-table-btn {
        position: absolute;
        top: 5px;
        right: 10px;
      }
      h5 {
        padding: 10px;
        margin: 0;
        line-height: 18px;
        border-bottom: solid 1px #dedede;
        background: #f5f7fa;
        color: #222;
        font-size: 14px;
        font-weight: 700;
      }
    }
    .zoon-search {
      padding: 6px 10px;
      border-bottom: solid 1px #dedede;
    }
    .table-list {
      padding-left: 0;
      margin-top: 0;
      height: calc(100% - 80px);
      box-sizing: border-box;
      list-style: none;
      overflow-y: scroll;
      .list-item {
        display: flex;
        align-items: center;
        padding: 8px 15px;
        line-height: 20px;
        border-bottom: solid 1px #dedede;
        cursor: pointer;
        color: #606266;
        font-size: 12px;
        &:hover,
        &.active {
          color: #1890ff;
        }
        .name {
          flex: 1;
          min-width: 0;
        }
        .list-opera {
          margin-left: left;
        }
      }
    }
    .table-empty {
      line-height: 60px;
      text-align: center;
      color: #909399;
      font-size: 12px;
    }
  }
  .el-table__row {
    .el-form-item {
      margin-bottom: 0;
      .el-form-item__error {
        left: 100%;
      }
    }
  }
}
</style>